package com.example.skywalking.config;

import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.jboss.logging.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.Inet4Address;

@Component
@WebFilter(filterName = "MDCFilter", urlPatterns = "/*")
public class MDCFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
        try {
            String uri = request.getRequestURI();
            String method = request.getMethod();
            String address = Inet4Address.getLocalHost().getHostAddress();
            MDC.put("uri", uri);
            MDC.put("method", method);
            MDC.put("address", address);
            MDC.put("requestId", TraceContext.traceId());
            chain.doFilter(request, response);
        } catch (Exception e) {
        } finally {
            MDC.clear();
        }
    }
}